﻿// 添加到Jquery对象上面，用$("#id").进行访问
; (function ($) {
    "use strict"; 
    $.fn.frameRadioBox = function (option, param) {
        if (typeof option == 'string') {
            return $.fn.frameRadioBox.methods[option](this, param);
        }
        var target = $(this);
        var targetId = target.attr('id');
        if (!targetId) {
            return false;
        }
        var _option = $.extend({
            url: null,
            key: "Key",
            value: "Value",
            data: null, // 数据源            
            dataName: 'data', // 数据名称
            onCheck: null,//选中事件
            default: undefined
        }, option);

        var dom = {
            loadData: function () {
                if (_option.url) {
                    $.ajax({
                        url: _option.url,
                        type: 'get',
                        dataType: 'json',
                        async: false,
                        cache: false,
                        success: function (data) { 
                            _option.data = data;
                            if (_option.dataName) {
                                if (_option.data != null) {
                                    _option.data = _option.data[_option.dataName];
                                }
                            } 
                        },
                        error: function (xhr, status, obj) {
                            throw exception;
                        }
                    });
                }
            },
            render: function (setting) { 
                if (setting.data && setting.data.length >= 0) {
                    var ref = target.attr('ref');
                    var name = targetId + "_radiobox";
                    var html = "";
                    $.each(setting.data, function (i) {
                        var row = setting.data[i];
                        html += "<label class='radio-box'>";
                        html += "<input type='radio' name='" + name + "' value='" + row[setting.key] + "' ref='" + ref + "' /> " + row[setting.value];
                        html += "</label>"; 
                    });
                    target.append(html);

                    if (setting.onCheck) {
                        $('input[type=radio][name=' + name + ']').on("ifChecked", setting.onCheck)
                    }
                }
                if (setting.default != undefined) {
                    target.frameRadioBox("setValue", setting.default);
                }
            }
        };
        dom.loadData();
        dom.render(_option);
        return target;
    };
    $.fn.frameRadioBox.methods = {
        getValue: function (target) {
            var value = "";
            $(target).find("div.checked").each(function (i, ele) {
                value += $(ele).find("input[type=radio]").val();
                value += ",";
            });
            if (value.indexOf(",") >= 0) {
                value = value.substring(0, value.length - 1);
            }
            return value;
        },
        setValue: function (target, value) {
            //if (frame.isNullOrEmpty(value)) {
            //    return;
            //}
            if (typeof value != 'string') {
                value = value.toString();
            }
            $(target).find("div").each(function (i, ele) {
                $(ele).removeClass('checked');
            });
            var ids = value.split(',');
            $.each(ids, function (i, val) {
                var radiobox = $(target).find('input[type=radio][value=' + val + ']');
                radiobox.attr("checked", true);
                radiobox.parent().addClass("checked");
            });
        }
    };

    $.fn.frameCheckBox = function (option, param) {
        if (typeof option == 'string') {
            return $.fn.frameCheckBox.methods[option](this, param);
        }
        var target = $(this);
        var targetId = target.attr('id');
        if (!targetId) {
            return false;
        }
        var _option = $.extend({
            url: null,
            key: "Key",
            value: "Value",
            data: null, //数据源
            dataName: 'data', //数据名称
            onCheck: null,//选中事件
            onUncheck: null,//取消选中事件
            onClick:null,
            default: undefined
        }, option);

        var dom = {
            loadData: function () {
                if (_option.url) {
                    $.ajax({
                        url: _option.url,
                        type: 'get',
                        dataType: 'json',
                        async: false,
                        cache: false,
                        success: function (data) { 
                            _option.data = data;
                            if (_option.dataName) {
                                if (_option.data != null) {
                                    _option.data = _option.data[_option.dataName];
                                }
                            }
                        },
                        error: function (xhr, status, obj) {
                            throw exception;
                        }
                    }); 
                }
            },
            render: function (setting) {
                if (setting.data && setting.data.length >= 0) { 
                    var name = targetId + "_checkbox";
                    var html = "";
                    $.each(setting.data, function (i) {
                        var row = setting.data[i];
                        html += "<label class='check-box'>";
                        html += "<input name='" + name + "' id='" + targetId +"' type='checkbox' value='" + row[setting.key] + "'>" + row[setting.value] + "</input>";
                        html += "</label>"; 
                    }); 
                    target.append(html);
                    if (setting.onCheck) {
                        $('input[type=checkbox][name=' + name + ']').on("ifChecked", setting.onCheck)
                    }
                    if (setting.onUncheck) {
                        $('input[type=checkbox][name=' + name + ']').on("ifUnchecked", setting.onUncheck)
                    }
                    if (setting.onClick) {
                        $('input[type=checkbox][name=' + name + ']').on("ifClicked", setting.onClick)
                    }
                }
                if (setting.default != undefined) { 
                    target.frameCheckBox("setValue", setting.default); 
                }
            }
        };
        dom.loadData();
        dom.render(_option);
        return target;
    };
    $.fn.frameCheckBox.methods = {
        getValue: function (target) {  
            var value = "";
            $(target).find("div.checked").each(function (i, ele) {
                value += $(ele).find("input[type=checkbox]").val();
                value += ",";
            });
            if (value.indexOf(",") >= 0) {
                value = value.substring(0, value.length - 1);
            }
            return value;
        },
        setValue: function (target, value) { 
            //if (frame.isNullOrEmpty(value)) {
            //    return;
            //}
            if (typeof value != 'string') {
                value = value.toString();
            }
            var ids = value.split(',');
            $.each(ids, function (i, val) {
                var checkbox = $(target).find('input[type=checkbox][value=' + val + ']');
                checkbox.attr("checked", true);
                checkbox.parent().addClass("checked");
            });
        }
    };

    $.fn.frameComboBox = function (option, param) {
        if (typeof option == 'string') {
            return $.fn.frameComboBox.methods[option](this, param);
        }
        var target = $(this);
        var targetId = target.attr('id');
        if (!targetId) {
            return false;
        }
        var _option = $.extend({
            url: null,
            key: "Key",
            value: "Value",
            maxHeight: "160px",
            class: null,
            multiple: false,
            search: false,//是否搜索框    
            isRequire: false,//是否必填项    
            data: null, //数据源          
            dataName: 'data',//数据名称
            onChange: null,
            default: undefined
        }, option);

        var dom = {
            loadData: function () {
                if (_option.url) {
                    $.ajax({
                        url: _option.url,
                        type: 'get',
                        dataType: 'json',
                        async: false,
                        cache: false,
                        success: function (data) {
                            _option.data = data;
                            if (_option.dataName) {
                                if (_option.data != null) {
                                    _option.data = _option.data[_option.dataName];
                                }
                            }
                        },
                        error: function (xhr, status, obj) {
                            throw exception;
                        }
                    }); 
                }
            },
            render: function (setting) {
                if (setting.data && setting.data.length >= 0) {
                    var id = targetId + "_select";

                    var mutiple = '';
                    if (setting.multiple) {
                        mutiple = 'multiple=""';
                    }
                    var html = "<select id='" + id + "' name='" + id + "' class='form-control " + frame.toString(setting.class) + (setting.isRequire == true ? "required" : "") + "' " + mutiple + " maxheight=" + setting.maxHeight + ">";
                    var selectExist = $("#" + id).length > 0;
                    if (selectExist) {
                        $("#" + id).empty();
                    }

                    var option = '';

                    var groupOption = false; // 是否有分组
                    if (setting.data.length > 0) {
                        groupOption = setting.data[0][setting.value] instanceof Array;
                    }
                    if (!setting.multiple) {
                        if (!groupOption) {
                            if (!setting.class) {
                                // 没有form-control这个class，就加一个全部选项，应该是查询条件
                                option += "<option value=''>请选择</option>";
                            } else {
                                if (!setting.multiple) {
                                    option += "<option value='' selected='selected'>请选择</option>";
                                }
                            }
                        }
                    }
                    $.each(setting.data, function (i) {
                        var row = setting.data[i];
                        if (typeof row == 'string') {
                            option += "<option value='" + row + "'>" + row + "</option>";
                        } else {
                            if (row[setting.value] instanceof Array) {
                                // 分组的选项
                                option += "<optgroup label='--" + row[setting.key] + "--'>";
                                $.each(row[setting.value], function (j) {
                                    var childRow = row[setting.value][j];
                                    option += "<option value='" + childRow[setting.key] + "'>" + childRow[setting.value] + "</option>";
                                });
                            }
                            else {
                                option += "<option value='" + row[setting.key] + "'>" + row[setting.value] + "</option>";
                            }
                        }
                    });
                    if (selectExist) {
                        $("#" + id).append(option);
                    }
                    else {
                        html += option;
                        html += "</select>";
                        target.append(html);

                        if (setting.onChange) {
                            $("#" + id).change(setting.onChange);
                        }
                    }
                    $("#" + id).select2({
                        minimumResultsForSearch: setting.search == true ? 0 : -1
                    })
                    // hack 搜索的select保持和其他元素的宽度一致
                    $("#" + targetId).find(".select2-container").width(280);

                    if (setting.default != undefined) {
                        target.frameComboBox("setValue", setting.default);
                    }

                }
            }
        };
        dom.loadData();
        dom.render(_option);
        return target;
    };
    $.fn.frameComboBox.methods = {
        getValue: function (target) {
            var valArray = $("#" + $(target).attr("id") + "_select").select2().val();
            if (valArray == null) {
                return "";
            }
            else {
                var val = valArray.toString();
                return val;
            }
        },
        setValue: function (target, value) {
            //if (frame.isNullOrEmpty(value)) {
            //    return;
            //}
            if (typeof value != 'string') {
                value = value.toString();
            }
            $("#" + $(target).attr("id") + "_select").val(value.split(',')).trigger("change");
        }
    };

    $.fn.frameTree = function (option, param) { 
        if (typeof option == 'string') {
            return $.fn.frameTree.methods[option](this, param);
        }
        var _option = $.extend({}, $.fn.frameTree.defaults, option || {});
        var target = $(this);
        var id = target.attr("id");

        // 显示垂直滚动条
        target.css("overflow-y", "auto").css("max-height", _option.maxHeight);

        frame.ajax({
            url: _option.url,
            async: _option.async,
            success: function (data) {
                var tree = $.fn.zTree.init($("#" + id), _option, data.data);
                for (var level = 0; level <= _option.expandLevel; level++) {
                    var nodes = tree.getNodesByParam("level", level);
                    for (var i = 0; i < nodes.length; i++) {
                        tree.expandNode(nodes[i], true, false, false);
                    }
                }
            }
        });
        return target;
    };
    $.fn.frameTree.methods = {
        getCheckedNodes: function (target, column) {
            var zTreeObj = $.fn.zTree.getZTreeObj($(target).attr("id"));
            var _column = frame.isNullOrEmpty(column) ? "id" : column;
            var nodes = zTreeObj.getCheckedNodes(true);
            return $.map(nodes, function (row) {
                return row[_column];
            }).join();
        },
        setCheckedNodes: function (target, ids) {
            if (!frame.isNullOrEmpty(ids)) {
                var _ids = ids.split(',');
                var zTreeObj = $.fn.zTree.getZTreeObj($(target).attr("id"));
                zTreeObj.cancelSelectedNode();//先取消所有的选中状态
                $.each(_ids, function (i, id) {
                    var node = zTreeObj.getNodeByParam("id", id);
                    zTreeObj.checkNode(node, true, false, true);
                });
            }
        },
        setCheckedNodesByName: function (target, names) {
            if (!frame.isNullOrEmpty(names)) {
                var _names = names.split(',');
                var zTreeObj = $.fn.zTree.getZTreeObj($(target).attr("id"));
                zTreeObj.cancelSelectedNode();//先取消所有的选中状态
                $.each(_names, function (i, name) {
                    var node = zTreeObj.getNodeByParam("name", name);
                    zTreeObj.checkNode(node, true, false, true);
                });
            }
        }
    };
    $.fn.frameTree.defaults = {
        url: '',
        async: false,
        maxHeight: "300px",
        expandLevel: 0,
        check: { "enable": false },
        view: { selectedMulti: false, nameIsHTML: true },
        data: { simpleData: { enable: true } },
        callback: {}
    };

    $.fn.frameComboBoxTree = function (option, param) { 
        if (typeof option == 'string') {
            return $.fn.frameComboBoxTree.methods[option](this, param);
        }
        var _option = $.extend({}, $.fn.frameComboBoxTree.defaults, option || {});

        var target = $(this);
        var id = target.attr("id");

        var eleInputId = id + "_input";
        var eleTreeId = id + "_tree";

        // 样式需要改成通用的
        target.css("position", "relative");
        var html = "<input id='" + eleInputId + "' name='" + eleInputId + "' readonly='readonly' type='text' class='form-control' placeholder='" + _option.placeholder + "' />";
        html += "<div id='" + eleTreeId + "' class='ztree treeSelect-panel' style='overflow-y: auto;max-height:" + _option.maxHeight + ";border:1px solid #e5e6e7;margin-top:1px;display:none'></div>";
        $(html).appendTo(target);

        $("#" + eleInputId).click(function () {
            var targetTree = $("#" + eleTreeId);
            if (targetTree.is(":hidden")) {
                targetTree.show();
            }
            else {
                targetTree.hide();
            }
        });

        frame.ajax({
            url: _option.url,
            async: _option.async,
            success: function (data) {
                var targetTree = $("#" + eleTreeId);
                var targetInput = $("#" + eleInputId);

                // 用户定义的onClick回调
                var customOnClick = _option.callback.customOnClick;
                // OnClick callback
                _option.callback.onClick = function (event, treeId, treeNode) {
                    var wholeName = '';
                    var wholeId = '';
                    var parentNode = treeNode;
                    //这里是输出完整的选中节点包括所有父节点A>A1>A1.1
                    //while (parentNode != null) {
                    //    wholeName = parentNode.name + '>' + wholeName;
                    //    wholeId = parentNode.id + ',' + wholeId;
                    //    parentNode = parentNode.getParentNode();
                    //}
                    //wholeName = frame.trimEnd(wholeName, '>');
                    //wholeId = frame.trimEnd(wholeId, ',');

                    //修改成只显示选中节点
                    wholeId = parentNode.id;
                    wholeName = parentNode.name;

                    target.attr("data-key", wholeId);
                    target.attr("data-value", wholeName);

                    targetInput.val(wholeName);
                    targetTree.hide();

                    if (customOnClick) {
                        customOnClick(event, treeId, treeNode);
                    }
                };

                target.ztree = $.fn.zTree.init($("#" + eleTreeId), _option, data.data);
                if (_option.expandLevel >= 0) {
                    for (var level = 0; level <= _option.expandLevel; level++) {
                        var nodes = target.ztree.getNodesByParam("level", level);
                        for (var i = 0; i < nodes.length; i++) {
                            target.ztree.expandNode(nodes[i], true, false, false);
                        }
                    }
                }
            }
        });

        $(document).click(function (e) {
            var e = e ? e : window.event;
            var tar = e.srcElement || e.target;
            if (!$(tar).hasClass('form-control')) {
                var tarId = $(tar).attr("id");
                if (frame.isNullOrEmpty(tarId) || tarId.indexOf("_tree") == -1) {
                    var targetTree = $("#" + eleTreeId);
                    targetTree.hide();
                    e.stopPropagation();
                }
            }
        });

        return target;
    };
    $.fn.frameComboBoxTree.methods = {
        getValue: function (target) {
            return $(target).attr("data-key");
        },
        setValue: function (target, value) { 
            var lastId = '0'; // 取最下面的一个值
            if (value) {
                var arr = value.toString().split(',');
                lastId = arr[arr.length - 1];
            }
            var id = target.attr("id");
            var eleTreeId = id + "_tree";
            var zTreeObj = $.fn.zTree.getZTreeObj(eleTreeId);
            var node = zTreeObj.getNodeByParam("id", lastId);
            if (node != null) {
                zTreeObj.cancelSelectedNode();//先取消所有的选中状态
                zTreeObj.selectNode(node, true);//将指定ID的节点选中
                zTreeObj.expandNode(node, true, false);//将指定ID节点展开
                zTreeObj.setting.callback.onClick('setValue', zTreeObj.setting.treeId, node); //触发onclick
            }
            return $(target);
        }
    };
    $.fn.frameComboBoxTree.defaults = {
        url: '',
        async: false,
        maxHeight: "200px",
        expandLevel: 0,
        placeholder: "请选择",
        check: { "enable": false },
        view: { selectedMulti: false, nameIsHTML: true },
        data: { simpleData: { enable: true } },
        callback: {}
    };

    $.fn.frameSelect = function (option, param) {
        if (typeof option == 'string') {
            return $.fn.frameSelect.methods[option](this, param);
        }
        var target = $(this);
        var targetId = target.attr('id');
        if (!targetId) {
            return false;
        } 
        var _option = $.extend({
            url: null,
            key: "Key",
            value: "Value",
            search: false,//是否搜索框    
            param: [],
            data: null,//数据源
            dataName: 'data',//数据名称
            onChange: null,
            tags: false,//是否允许创建新标签,在文本框输入值
            allowClear: false,//是否显示清除按钮,需要同时配置placeholder，否则可能会引起js报错
            placeholder:null
        },option)
        var dom = {
            loadData: function () { 
                if (_option.url) {
                    $.ajax({
                        url: _option.url,
                        type: 'get',
                        dataType: "json",
                        data: _option.param,
                        async: false,
                        cache: false,
                        success: function (data) { 
                            _option.data = data; 
                            if (_option.dataName) {
                                if (_option.data != null) {
                                    _option.data = _option.data[_option.dataName]; 
                                }
                            }
                        },
                        error: function (xhr, status, obj) {
                            throw exception;
                        }
                    });
                }
            },
            render: function (setting) { 
                if (setting.data && setting.data.length >= 0) {
                    $.each(setting.data, function (i) { 
                        var row = setting.data[i];
                        target.append($("<option></option>").val(row[setting.key]).html(row[setting.value]));
                    }); 
                    target.select2({
                        minimumResultsForSearch: setting.search == true ? 0 : -1,
                        tags: _option.tags,
                        allowClear: _option.allowClear,
                        placeholder: _option.placeholder
                    });
                    if (setting.onChange) {
                        $("#" + targetId).change(setting.onChange);
                    }
                    if (setting.default != undefined) {
                        target.frameSelect("setValue", setting.default);
                    }
                }
            }
        }
        dom.loadData();
        dom.render(_option);
        return target;
    }
    $.fn.frameSelect.methods = {
        getValue: function (target) {
            var valArray = $("#" + $(target).attr("id")).select2().val();
            if (valArray == null) {
                return "";
            }
            else {
                var val = valArray.toString();
                return val;
            }
        },
        setValue: function (target, value) { 
            //if (frame.isNullOrEmpty(value)) {
            //    return;
            //}
            if (typeof value != 'string') {
                value = value.toString();
            }  
            $("#" + $(target).attr("id")).val(value.split(',')).trigger("change");
        }
    }

    $.fn.formSerialize = function () { 
        var element = $(this);
        var postdata = {};
        postdata["Id"] = frame.request("id");
        element.find('input,select,textarea').each(function (r) { 
            var $this = $(this);
            var id = $this.attr('id');
            var type = $this.attr('type');
            switch (type) {
                case "checkbox":
                    postdata[id] = $this.is(":checked");
                    break;
                default: 
                    postdata[id] = $this.val()
                    break;
            }
        });
        return postdata;
    };
    $.fn.frameSerialize = function (value) {  
        var data = {};
        if (value && typeof value == 'object') {
            data = value;
        }
        data["Id"] = frame.request("id");
        $(this).find('input,select,textarea,[col]').each(function (i, control) {
            var id = $(control).attr("id");
            var field = $(control).attr("col");  
            if (!!id && !!field) { 
                if (control.tagName == "INPUT") {
                    if (control.type == "checkbox") {
                        if ($(control).prop("checked")) {
                            if (data[field]) {
                                data[field] = data[field] + "," + $(control).val();
                            } else {
                                data[field] = $(control).val();
                            }
                        }
                    }
                    else if (control.type == "radio") {
                        if ($(control).prop("checked")) {
                            data[field] = $(control).val();
                        }
                    }
                    else {
                        data[field] = $(control).val();
                    }
                }
                else if (control.tagName == "SELECT") {
                    data[field] = $(control).val();
                }
                else if (control.tagName == "DIV") {
                    if ($(control).find("#" + id + "_tree").length > 0) {
                        data[field] = $(control).frameComboBoxTree("getValue");
                    } else if ($(control).find("#" + id + "_select").length > 0) {
                        data[field] = $(control).frameComboBox("getValue");
                    }
                    else if ($(control).find("input[type=checkbox]").length > 0) {
                        data[field] = $(control).frameCheckBox("getValue");
                    } else if ($(control).find("input[type=radio]").length > 0) {
                        data[field] = $(control).frameRadioBox("getValue");
                    } else {
                        data[field] = $(control).html();
                    }
                }
                else if (control.tagName == "IMG") {
                    data[field] = $(control).prop("src");
                }
                else if (control.tagName == "SPAN") {
                    if ($(control).find("#" + id + "_select").length > 0) {
                        data[field] = $(control).frameComboBox("getValue");
                    } else {
                        data[field] = $(control).html();
                    }
                }
                else if (control.tagName == "TEXTAREA") {
                    data[field] = $(control).val();
                }
            }
        }); 
        return data;
    };
    $.fn.getWebControls = function (value) { 
        var data = {};
        if (value && typeof value == 'object') {
            //追加对象
            //$('#form').getWebControls({ Id: id });
            data = value;
        }
        $(this).find("[col]").each(function (i, control) {
            var id = $(control).attr("id");
            var field = $(control).attr("col"); 
            if (control.tagName == "INPUT") {
                if (control.type == "checkbox") {
                    if ($(control).prop("checked")) {
                        if (data[field]) {
                            data[field] = data[field] + "," + $(control).val();
                        } else {
                            data[field] = $(control).val();
                        }
                    }
                }
                else if (control.type == "radio") {
                    if ($(control).prop("checked")) {
                        data[field] = $(control).val();
                    }
                }
                else {
                    data[field] = $(control).val();
                }
            }
            else if (control.tagName == "SELECT") {
                data[field] = $(control).val();
            } 
            else if (control.tagName == "DIV") { 
                if ($(control).find("#" + id + "_tree").length > 0) {
                    data[field] = $(control).frameComboBoxTree("getValue");
                } else if ($(control).find("#" + id + "_select").length > 0) {
                    data[field] = $(control).frameComboBox("getValue");
                }
                else if ($(control).find("input[type=checkbox]").length > 0) {
                    data[field] = $(control).frameCheckBox("getValue");
                } else if ($(control).find("input[type=radio]").length > 0) {
                    data[field] = $(control).frameRadioBox("getValue");
                } else {
                    data[field] = $(control).html();
                }
            }
            else if (control.tagName == "IMG") {
                data[field] = $(control).prop("src");
            }
            else if (control.tagName == "SPAN") {
                if ($(control).find("#" + id + "_select").length > 0) {
                    data[field] = $(control).frameComboBox("getValue");
                } else {
                    data[field] = $(control).html();
                }
            }
            else if (control.tagName == "TEXTAREA") {
                data[field] = $(control).val();
            }
        });
        return data;
    }; 
    $.fn.setWebControls = function (data) {
        $(this).find("[col]").each(function (i, control) { 
            var id = $(control).attr("id");
            var field = $(control).attr("col");
            if (control.tagName == "INPUT") {
                if (control.type == "checkbox") {
                    if ($(control).val() == data[field]) {
                        $(control).prop("checked", "checked");
                    }
                }
                else if (control.type == "radio") {
                    if ($(control).val() == data[field]) {
                        if ($(control).iCheck) {
                            $(control).iCheck('check');
                        }
                        else {
                            $(control).prop("checked", true);
                        }
                    }
                }
                else {
                    $(control).val(data[field]);
                }
            }
            else if (control.tagName == "SELECT") { 
                $(control).val(data[field]).trigger("change");
            }
            else if (control.tagName == "DIV") {
                if ($(control).find("#" + id + "_tree").length > 0) {
                    $(control).frameComboBoxTree("setValue", data[field]);
                } else if ($(control).find("#" + id + "_select").length > 0) {
                    $(control).frameComboBox("setValue", data[field]);
                } else if ($(control).find("input[type=checkbox]").length > 0) {
                    $(control).frameCheckBox("setValue", data[field]);
                } else if ($(control).find("input[type=radio]").length > 0) {
                    $(control).frameRadioBox("setValue", data[field]);
                } else {
                    $(control).html(data[field]);
                }
            }
            else if (control.tagName == "SPAN") {
                $(control).html(data[field]);
            }
            else if (control.tagName == "TEXTAREA") {
                $(control).val(data[field]);
            }
        });
        return data;
    }
    $.fn.bindSelectByUrl = function (options) {
        var defaults = {
            key: "Key",
            value: "Value",
            search: false,//是否搜索框
            url: "",
            param: [],
            change: null,
            tags: false//是否允许创建新标签,在文本框输入值
        };
        var options = $.extend(defaults, options);
        var $element = $(this);
        if (options.url != "") {
            $.ajax({
                url: options.url,
                data: options.param,
                dataType: "json",
                async: false,
                success: function (data) {
                    $.each(data, function (i) {
                        $element.append($("<option></option>").val(data[i][options.key]).html(data[i][options.value]));
                    });
                    $element.select2({
                        minimumResultsForSearch: options.search == true ? 0 : -1,
                        tags: options.tags
                    });
                    $element.on("change", function (e) {
                        if (options.change != null) {
                            options.change(data[$(this).find("option:selected").index()]);
                        }
                        $("#select2-" + $element.attr('id') + "-container").html($(this).find("option:selected").text().replace(/　　/g, ''));
                    });
                }
            });
        } else {
            $element.select2({
                minimumResultsForSearch: -1
            });
        }
    }
    $.fn.bindSelectByEnum = function (options) {
        var defaults = {
            key: "Key",
            value: "Value",
            search: false,//是否搜索框    
            change: null,
            data: null, //数据源          
            dataName: 'data'//数据名称
        };
        var options = $.extend(defaults, options);
        var $element = $(this);
        if (options.data && options.data.length >= 0) {
            $.each(options.data, function (i) {
                $element.append($("<option></option>").val(options.data[i][options.key]).html(options.data[i][options.value]));
            });
            $element.select2({
                minimumResultsForSearch: options.search == true ? 0 : -1
            });
            $element.on("change", function (e) {
                if (options.change != null) {
                    options.change(options.data[$(this).find("option:selected").index()]);
                }
                $("#select2-" + $element.attr('id') + "-container").html($(this).find("option:selected").text().replace(/　　/g, ''));
            });
        } else {
            $element.select2({
                minimumResultsForSearch: -1
            });
        }
    }

})(window.jQuery);